#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>

#define N 2
#define NUM 1024
using namespace std;

void writer(int wfd)
{
    string s = "hello world";
    pid_t ret = getpid();
    // int number = 1024;
    int number = 0;
    char buffer[NUM];
    while (true)
    {
        buffer[0] = 0;
        snprintf(buffer, sizeof(buffer), "%s-%d-%d", s.c_str(), ret, number++);
        //  cout << buffer << endl;
        write(wfd, buffer, strlen(buffer));
        // char c = 'c';
        // write(wfd, &c, 1);
        //  number++;

        // cout << number << endl;
        sleep(1);
    }
}

void reader(int rfd)
{
    // sleep(5);
    char buffer[NUM];
    int cnt = 5;
    while (cnt--)
    {
        // sleep(50);
        buffer[0] = 0;
        ssize_t n = read(rfd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            cout << "i am parent[" << getpid() << "]" << buffer << endl;
        }
        else
        {

            cout << "read fail" << endl;
            break;
        }
    }
}

int main()
{
    int pipefd[N] = {0};
    int n = pipe(pipefd);
    if (n < 0)
        return 1;
    // cout << pipefd[0] << pipefd[1] << endl;
    pid_t rid = fork();
    if (rid < 0)
        return 2;
    if (rid == 0)
    {
        // child
        close(pipefd[0]);
        writer(pipefd[1]);

        close(pipefd[1]);
        exit(0);
    }
    close(pipefd[1]);

    reader(pipefd[0]);

    close(pipefd[0]);
    cout << "father close read fd:" << pipefd[0] << endl;
    sleep(5);
    int status = 0;
    pid_t wt = waitpid(rid, &status, 0);
    cout << "pid:" << rid << "exit code:" << ((status >> 8) & 0xFF) << "exit signs" << (status & 0x7F) << endl;
    sleep(5);
    return 0;
}
